package net.tv90.bfmccoreqqbot.api;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import net.tv90.bfmccoreqqbot.api.config.WebSocketConfig;
import net.tv90.bfmccoreqqbot.api.entity.MessageContext;
import net.tv90.bfmccoreqqbot.api.entity.lagrange.Message;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

import java.io.IOException;
import java.net.URI;


public class WebSocketClientInitializer {

    public static WebSocketClient client = null;
    public static WebSocketConfig config;
    public static int connectCount = 0;
    protected static MessageDispatcher messageDispatcher;

    static {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        mapper.findAndRegisterModules();
        try {
            config = mapper.readValue(WebSocketClientInitializer.class.getClassLoader().getResourceAsStream("config.yml"), WebSocketConfig.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public WebSocketClientInitializer() {
    }

    public static void init(String url) {
        System.out.println("初始化URL成功" + url);
        connect();
    }

    public synchronized static void connect() {
        client = new WebSocketClient(URI.create(config.getUrl()), new Draft_6455()) {
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
                connectCount++;
                System.out.println("连接成功，连接数量为 " + connectCount + " ，正在监听反向代理地址 " + config.getUrl());
            }

            @Override
            public void onMessage(String json) {
                if (config.isDebug()) {
                    System.out.println("收到消息");
                    System.out.println(json);
                }
                switch (config.getCore()) {
                    case "lagrange": {
                        Message msg = JSONObject.parseObject(json, Message.class);
                        if (msg != null && "message".equals(msg.getPost_type()) && msg.getSender() != null) {
                            MessageContext messageContext = MessageContext.builder()
                                    .message(msg.getRaw_message())
                                    .rawMessage(msg.getRaw_message())
                                    .senderGroupQq(msg.getGroup_id())
                                    .senderNickname(msg.getSender().getNickname())
                                    .senderQq(String.valueOf(msg.getSender().getUser_id()))
                                    .senderRole(msg.getSender().getRole())
                                    .build();
                            if (config.isDebug()) {
                                System.out.println("成功解析消息");
                                System.out.println(messageContext);
                            }
                            messageDispatcher.dispatch(messageContext);
                        } else {
                            if (config.isDebug()) {
                                System.out.println("解析消息失败");
                                System.out.println(msg);
                            }
                        }
                        break;
                    }
                    case "gocqhttp": {
                        net.tv90.bfmccoreqqbot.api.entity.gocqhttp.Message msg =
                                JSONObject.parseObject(json, net.tv90.bfmccoreqqbot.api.entity.gocqhttp.Message.class);
                        if (msg != null && "message".equals(msg.getPost_type()) && msg.getSender() != null) {
                            MessageContext messageContext = MessageContext.builder()
                                    .message(msg.getMessage())
                                    .rawMessage(msg.getRaw_message())
                                    .senderGroupQq(msg.getGroup_id())
                                    .senderNickname(msg.getSender().getNickname())
                                    .senderQq(msg.getSender().getUser_id())
                                    .senderRole(msg.getSender().getRole())
                                    .build();
                            if (config.isDebug()) {
                                System.out.println("成功解析消息");
                                System.out.println(messageContext);
                            }
                            messageDispatcher.dispatch(messageContext);
                        } else {
                            if (config.isDebug()) {
                                System.out.println("解析消息失败");
                                System.out.println(msg);
                            }
                        }
                        break;
                    }
                    default: {
                        throw new RuntimeException("不支持的Http核心");
                    }
                }

            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                System.out.println("连接关闭");
                connectCount--;
            }

            @Override
            public void onError(Exception ex) {
                System.out.println("连接错误");
                ex.printStackTrace();
            }
        };
        client.connect();
        int connectNum = 0;
        while (!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
            if (++connectNum > config.getMaxConnections()) {
                return;
            }
        }
    }
}
